<?php
require 'Admin/Model/Model.php';
	class UserModel extends Model{
		function __Construct(){
			parent::__Construct();
		}
		function getUserList(){
			/*$data = array(
			array('uname'=>'jason','gender'=>'男'),
			array('uname'=>'jack','gender'=>'男')
			);*/
			$sql = "select * from users";
		    $data = $this->conn->query($sql);
			return $data;
		}
		function addUser($data){
			if(!empty($_FILES["pic"]["name"])){
  				$pic = $this->uploadfile('pic','./upload/',array('jpg','gif','png'));
  				}
			  else{
			  	$pic='';
			  }

			  $user = array(
					'uname' => trim($data['uname']),  
					'password' => $data['password'],
					'gender' => $data['gender'],
					'birthdate' => $data['birthdate'],
					'hobby' => implode($data['hobby'], ','),
					'degree' => $data['degree'],
					'intro' => $data['intro'],
					'pic'=>$pic
			  	);
			  $keys = implode(',',array_keys($user));
			  $values = implode("','", array_values($user));
			  $sql="insert into users ({$keys}) VALUES ('{$values}')";
			  //执行SQL语句
				$result = $this->conn->query($sql);
					return $result;
			  
		}
		function getUserByID($id){
			$sql = "select * from users where uid=".$id;
		    $result = $this->conn->query($sql);
		    var_dump($result);
	      	return $result;
		}

		function updateUser($data){
			//var_dump($data);
			$user = array(
					'uname' => trim($data['uname']),  
					//'password' => $data['password'],
					'gender' => $data['gender'],
					'birthdate' => $data['birthdate'],
					'hobby' => implode($data['hobby'], ','),
					'degree' => $data['degree'],
					'intro' => $data['intro'],
			  	);
			if(!empty($_FILES["pic"]["name"])){
				$r=$this->conn->query("select * from users where uid= ".$data['id']);
				$pic1=$r['pic'];
  				$pic = $this->uploadfile('pic','./upload/',array('jpg','gif','png'));
  				$user['pic'] = $pic;
  				if(strcmp($pic,$pic1 ))
  				{
  					unlink('./upload/'.$pic1);
  					echo "删除旧头像<br>";
  				}
  				}
  			else
  				echo "没有修改头像<br>";	  
			 $sets = '';
			  foreach ($user as $key=>$val){
			        $sets.=$key."='".$val."',";
			  }
			    $sets=rtrim($sets,','); //去掉SQL里的最后一个逗号
			   
			    $sql="UPDATE users SET {$sets} where uid=".$data['id'];
			  //执行SQL语句
				$result = $this->conn->query($sql);
					return $result;
			  
		}

		function delUser($id){
			$sql1 = "select * from users where uid=".$id;
			$data1 = $this->conn->query($sql1);
			$filepath="./upload/".$data1['pic'];
			if(file_exists($filepath))
				{
					unlink($filepath);
					echo "头像删除成功".'<br>';
				}	
			else
				echo "头像删除失败".'<br>';
			$sql = "delete from users where uid=".$id;
			
			$result = $this->conn->query($sql);
			return $result;
		}
		function Search($data){
			//var_dump($data);
			$sql="select * from users where uname like '%".$data."%'";
			var_dump($sql);
			$result = $this->conn->query($sql);
			var_dump($result);
			return $result;
		}
	}
?>